package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.dao.UserMapper;
import com.itheima.entity.Permission;
import com.itheima.dao.PermissionMapper;
import com.itheima.entity.User;
import com.itheima.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.utils.MenuTree;
import com.itheima.vo.RolePermissionVo;
import com.itheima.vo.query.PermissionQueryVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zzy
 * @since 2024-05-30
 */
@Service
@Transactional
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Resource
    private UserMapper userMapper;
    /**
     * 根据用户ID查询权限列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<Permission> findPermissionListByUserId(Long userId) {
        return baseMapper.findPermissionListByUserId(userId);
    }

    @Override
    public List<Permission> findPermissionList(PermissionQueryVo permissionQueryVo) {
        //创建条件构造器对象
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<Permission>();
//排序
        queryWrapper.orderByAsc("order_num");
//调用查询菜单列表的方法
        List<Permission> permissionList = baseMapper.selectList(queryWrapper);
//生成菜单树
        List<Permission> menuTree = MenuTree.makeMenuTree(permissionList, 0L);
//返回数据
        return menuTree;
    }

    @Override
    public List<Permission> findParentPermissionList() {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<Permission>();
//只查询type为目录和菜单的数据(type=0或type=1)
        queryWrapper.in("type", Arrays.asList(0,1));
//排序
        queryWrapper.orderByAsc("order_num");
//查询菜单数据
        List<Permission> permissionList = baseMapper.selectList(queryWrapper);
//构造顶级菜单信息，如果数据库中的菜单表没有数据，选择上级菜单时则显示顶级菜单
        Permission permission = new Permission();
        permission.setId(0L);
        permission.setParentId(-1L);
        permission.setLabel("顶级菜单");
        permissionList.add(permission);//将顶级菜单添加到集合
//生成菜单数据
        List<Permission> menuTree = MenuTree.makeMenuTree(permissionList, -1L);
//返回数据
        return menuTree;
    }

    @Override
    public boolean hasChildrenOfPermission(Long id) {
        //创建条件构造器对象
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<Permission>();
//查询父级ID
        queryWrapper.eq("parent_id", id);
//判断数量是否大于0，如果大于0则表示存在
        if(baseMapper.selectCount(queryWrapper)>0){
            return true;
        }
        return false;
    }
    //查询菜单树
    @Override
    public RolePermissionVo findPermissionTree(Long userId,Long roleId){
        //查询当前用户信息
        User user=userMapper.selectById(userId);
        //创建集合保存当前权限菜单
        List<Permission>list=null;
        //判断当前用户是否是管理员是则返回全部菜单否则根据用户id查询用户全部菜单信息
        if(user!=null&&!ObjectUtils.isEmpty(user.getIsAdmin())&&user.getIsAdmin()==1){
            list=baseMapper.selectList(null);
        }
        else{
            list=baseMapper.findPermissionListByUserId(userId);
        }
        //将当前用户所拥有的权限封装成菜单树
        List<Permission>permissionList=MenuTree.makeMenuTree(list,0L);
        //查询要分配角色拥有的权限列表
        List<Permission>rolePermissions=baseMapper.findPermissionListByRoleId(roleId);
        //创建集合保存权限ID
        List<Long>listIds=new ArrayList<Long>();
        //进行数据回显
        Optional.ofNullable(list).orElse(new ArrayList<>()).
                stream().filter(Objects::nonNull).forEach(item->{
                    Optional.ofNullable(rolePermissions).orElse(new ArrayList<>())
                            .stream().filter(Objects::nonNull)
                            .forEach(obj->{
                                if(item.getId().equals(obj.getId())){
                                    listIds.add(obj.getId());
                                            return;
                                }
                            });
                        }
                );
        RolePermissionVo vo=new RolePermissionVo(permissionList, listIds.toArray());
        return vo;
    }
}
